//
//  FriendLog.swift
//  HealthMonitoring
//
//  Created by YTYanK on 2018/7/17.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

/**
 亲友日志
 **/

import UIKit
import SwiftyJSON

protocol FriendLogCellDelegate: class {
    func clickBtn(isAccept: Bool, selectRowAt indexPath: IndexPath, userId: String?)
}

class FriendLogCell: HMTableViewCell {
    let headPortrait = UIImageView()
    let nameLabel = UILabel()
    let isolatingLine = UIView()
    let setUp = UIButton()
    var delegate: FriendLogCellDelegate?
    var cellIndexPath: IndexPath?
    var id = "" // 用户id
    var phone = ""
    var isAcceptBtn = false
    
    override func setupViews(view: UIView) {
        view.addSubview(headPortrait)
        view.addSubview(nameLabel)
        view.addSubview(isolatingLine)
        view.addSubview(setUp)
        
      
        headPortrait.centerYAlign(view: view)
        headPortrait.leadingAlign(view: view, predicate: "20")
        headPortrait.widthConstrain(predicate: "60")
        headPortrait.heightConstrain(predicate: "60")
        headPortrait.layer.masksToBounds = true
        headPortrait.layer.cornerRadius = 30    //cornerRadius = 60/2
//        headPortrait.imgName(name: "dveice_tz.png")
        
        nameLabel.centerYAlign(view: view)
        nameLabel.leadingHorizontally(view: headPortrait, predicate: "20")
//        nameLabel.text = "xxxxxx---xxxxx--xxxx"
        

        
        isolatingLine.leadingHorizontally(view: nameLabel, predicate: "10")
        isolatingLine.centerYAlign(view: view)
        isolatingLine.backgroundColor  = configure.shareConfigure.HMColor1
        isolatingLine.widthConstrain(predicate: "1")
        isolatingLine.height(view: view, predicate: "*0.5")

        
        setUp.leadingHorizontally(view: isolatingLine, predicate: "20")
        setUp.centerYAlign(view: view)
        setUp.trailingAlign(view: view, predicate: "-20")
        setUp.height(view: view, predicate: "*0.5")
        setUp.widthConstrain(predicate: "50")
        setUp.setTitle(nil, for: .normal)
        setUp.backgroundColor = UIColor.clear
        setUp.setImage(UIImage.init(named: "configure.png"), for: .normal)
        setUp.addTarget(self, action: #selector(setupClick), for: UIControlEvents.touchUpInside)

    }
    
    @objc func setupClick(sender: UIButton) {
        delegate?.clickBtn(isAccept: isAcceptBtn, selectRowAt: self.cellIndexPath!, userId: id)
    }
    
    
    override func setJson(json: JSON) {
        
        let urlString =  configure.shareConfigure.IP_diagonal  + json["iconUrl"].stringValue
        headPortrait.img(url: urlString)  //imgName(name: urlString)
        
        if json["id"].stringValue.count > 0 {
          id = json["id"].stringValue
        }
        
        if json["userId"].stringValue.count > 0 {
           id = json["userId"].stringValue
        }
        
        phone = json["phone"].stringValue
        nameLabel.text = json["nickname"].stringValue
        
        if isAcceptBtn {
            isolatingLine.isHidden = isAcceptBtn
            
            setUp.layer.cornerRadius = 8
            setUp.setTitle("接受", for: .normal)
            setUp.backgroundColor = configure.shareConfigure.HMColor1
            setUp.setImage(nil, for: .normal)
        }
    }
}



/// 亲友日志
class FriendLog: HMTableViewController {
    // 数据
    var flJsonData = JSON()
    
    private lazy var dragView: HMDragImageView = {
        let _dure = HMDragImageView.init(frame: CGRect.init(x: 30, y: 600, width: 80, height: 80))
        _dure.backgroundColor = configure.shareConfigure.HMColor1
        _dure.layer.cornerRadius = 40
        //_dure.layer.masksToBounds = true
        let l = UILabel()
         l.text = "添加亲友"
         l.textColor = UIColor.white
        _dure.addSubview(l)
         l.centerXYAlign(view: _dure)

        _dure.setActionBlock {
            print("------>>回调")
           let sear =  HMSearchFriend()
           self.pushViewController(sear)
        }
        return _dure
    }()
    
    
    //
    func setNavRightView()  {
        let setBtn =  UIButton(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
        setBtn.setImage(UIImage(named: "smg"), for: .normal)
        let rightBtn = UIBarButtonItem(customView: setBtn)
        setBtn.addTarget(self, action: #selector(navRightBtn), for: UIControlEvents.touchUpInside)
        let negativeSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        negativeSpacer.width = -10
        
        navigationItem.rightBarButtonItems = [negativeSpacer, rightBtn]
    }
    @objc func navRightBtn() {
//        NetRequestTool.shareInstance.met = .get
//        NetRequestTool.request(url: "friend/requests", parameters: [:], success: { (json) in
            let newFriend = HMNewFriend()
//            newFriend.nfJsonData = json["data"]
            self.pushViewController(newFriend)
//        }, fail: { (code, msg) in
//            RKDropdownAlert.title("温馨提醒!", message: "获取数据失败（\(code)）！")
//        }) {}
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavRightView()
//        super.hideHeader()
        super.hideFooter()
    }
    
    /// 请求，再来一次
    func agianRequest() {
        NetRequestTool.shareInstance.met = .get
        NetRequestTool.request(url: "friend/list", parameters: [:], success: { (json) in
            self.flJsonData = json["data"]
            self.tableView.reloadData()
        }, fail: { (code, msg) in
             RKDropdownAlert.title("温馨提醒!", message: "获取数据失败（\(code)）！")
        }) { }
    }
   
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.dragView.removeFromSuperview()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated) // 将要显示
        let app =  UIApplication.shared.delegate as! AppDelegate
        app.window!.addSubview(self.dragView)
        agianRequest()
    }
    
    override func load() {
        self.title = "亲友日志"
        self.tableView.register(FriendLogCell.classForCoder(), forCellReuseIdentifier: "FriendLogCell")
    }
    
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.flJsonData.count
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return  88
    }
    
    override func cellForRow(atIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "FriendLogCell") as! FriendLogCell
        cell.delegate = self
        cell.cellIndexPath = indexPath as IndexPath
        cell.setJson(json: self.flJsonData[indexPath.row])
        return cell
    }
    
}

extension FriendLog: FriendLogCellDelegate {
    func clickBtn(isAccept: Bool, selectRowAt indexPath: IndexPath, userId: String?) {
    
            let details = HMDetails()
            details.isBecomeFriend = true
            details.userJsonData =  self.flJsonData[indexPath.row]   //json["data"]
            self.pushViewController(details)
            

    }
}
